package com.javaforever.gatescore.tool;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class FileStringReplaceTool  extends JFrame implements MouseListener, ActionListener {
	private static final long serialVersionUID = 1L;
	protected JTextArea source;
	protected JTextArea target;
	protected JLabel  sourcelbl;
	protected JLabel targetlbl;
	protected JTextField sourcePath;
	protected JTextField targetPath;
	protected JButton replaceBtn;
	protected JScrollPane sourcePane;
	protected JScrollPane targetPane;
		
	public FileStringReplaceTool() throws Exception{
		super("无垠式代码生成器文件字符串替换助手");
		
//		String windows="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
//		UIManager.setLookAndFeel(windows);		
//		UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel pPanel = new JPanel();
		BorderLayout layout = new BorderLayout();
		pPanel.setLayout(layout);	
		
		JPanel jpl = new JPanel();
		jpl.setSize(1600,200);
		jpl.setLayout(new FlowLayout());
		Font myFont = new Font("wqy", Font.PLAIN, 20);
		sourcelbl = new JLabel("Source Path:");
		targetlbl = new JLabel("Target Path:");
		sourcePath = new JTextField("D:\\JerryWork\\Workbench\\source",22);
		targetPath = new JTextField("D:\\JerryWork\\Workbench\\target",22);
		
		sourcePath.setFont(myFont);
		targetPath.setFont(myFont);
		jpl.add(sourcelbl);
		jpl.add(sourcePath);
		jpl.add(targetlbl);
		jpl.add(targetPath);
		
		replaceBtn = new JButton("Replace");
		replaceBtn.addActionListener(this);
		jpl.add(replaceBtn);
		
		
		
		JPanel contentPane = new JPanel();
		source = new JTextArea(200,60);
		Font sfont=new Font("宋体",Font.PLAIN,14); 
		//source.setFont(sfont);
		sourcePane = new JScrollPane(source,  JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
			    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		sourcePane.setSize(550,400);
		sourcePane.setVisible(true);
		target = new JTextArea(200,60);
		//target.setFont(sfont);
		targetPane = new JScrollPane(target,  JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
			    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		targetPane.setSize(550,400);
		targetPane.setVisible(true);
		contentPane.add(sourcePane);
		contentPane.add(targetPane);
		contentPane.setSize(1200,400);

		
		layout.addLayoutComponent(jpl, BorderLayout.NORTH);
		pPanel.add(jpl);
		layout.addLayoutComponent(contentPane, BorderLayout.CENTER);
		pPanel.add(contentPane);
		this.setContentPane(pPanel);
		setSize(1200, 700);
		setLocationRelativeTo(null);//窗口在屏幕中间显示
		setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			if (e.getSource() == replaceBtn) {
				String sourcePathStr = sourcePath.getText().trim();
				String targetPathStr = targetPath.getText().trim();
				
				File [] files = Paths.get(sourcePathStr).toFile().listFiles();
				for (File f:files) {
					if (f.isFile()) {
						String targetFStr = targetPathStr +"/"+ f.getName();
						String sourceText = new String(source.getText().getBytes( "UTF-8"));
						String targetText = new String(target.getText().getBytes( "UTF-8"));
						String content =  new String(Files.readAllBytes(f.toPath()),"GBK");
//						content = new String(content.getBytes(),"GBK");
//						List<String>contents = Files.readAllLines(f.toPath(),Charset.forName("GBK"));
//						String [] contentss = contents.toArray(new String[contents.size()]);					
//						String content = String.join("\n",contentss);
//						content = new String(content.getBytes("UTF-8"));
						String targetcontent = content.replace(sourceText, targetText);
						writeToFile(targetFStr,targetcontent);
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void writeToFile(String filePath, String content) throws Exception {
		File f = new File(filePath);
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		f.createNewFile();
		try (Writer fw = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(f.getAbsolutePath()), "GBK"))) {
			fw.write(content, 0, content.length());
		}
	}

	private Integer countFrpmtSpaceTabs(String s) {
		Integer spaces = 0;
		for (int i=0;i<s.length();i++) {
			if (s.charAt(i)==' ') spaces += 1;
			else if (s.charAt(i)=='\t') spaces += 4;
			else break;
		}
		return (int)Math.ceil(spaces/4);
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	public static void main(String [] args) {
		try{	
			java.awt.EventQueue.invokeLater(new Runnable() {

	            @Override
	            public void run() {
	            	try {
	            		new FileStringReplaceTool().setVisible(true);
	            	} catch (Exception e){
	            		e.printStackTrace();
	            	}
	            }
	        });
		} catch (Exception e){
			JOptionPane.showMessageDialog(null, e.getMessage(), "信息", JOptionPane.ERROR_MESSAGE);
		}
	}
}
